﻿using CNKI.Graduate.Framework.Platform;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CNKI.Graduate.Framework.Log
{
    /// <summary>
    /// 统一处理系统运行日志控制台输出
    /// </summary>
    class WriteLogger
    {
        private static bool isDebug = false;
        static WriteLogger()
        {
            GetDebugMode();
            GetOverDays();
        }
        /// <summary>
        /// Actually sends the message to the underlying log system.
        /// </summary>
        /// <param name="level">the level of this log event.</param>
        /// <param name="message">the message to log</param>
        /// <param name="exception">the exception to log (may be null)</param>
        public static void WriteInternal(LogLevel level, object message, Exception exception)
        {
            try
            {
                DateTime timeStamp = DateTime.Now;

                string result = string.Format("{0} [{1}] {2}",
                    timeStamp, level, message);

                if (exception != null)
                {
                    result = string.Format("{0}{1}{2}", result, Environment.NewLine, exception.ToString());
                }
                if (isDebug)
                {
                    // 日志输出到控制台信息
                    Console.WriteLine(result);
                    WriteLogList(result);
                }
                else
                {
                    if (level == LogLevel.Error 
                        || level == LogLevel.Fatal
                        ||level==LogLevel.Warn
                        || level == LogLevel.Info)
                    {
                        WriteLogList(result);
                    }
                }
               
              
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.ToString()));
            }
        }

        private static void GetDebugMode()
        {
            try
            {
                string mode = System.Configuration.ConfigurationManager.AppSettings["LogMode"].Trim();
                if (mode == "Debug")
                {
                    isDebug= true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.ToString()));
            }
            isDebug = false;


        }
        private static void GetOverDays()
        {
            try
            {
                string num = System.Configuration.ConfigurationManager.AppSettings["LogOverDays"].Trim();
                OverDays = int.Parse(num);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.ToString()));
            }
            OverDays = 60;
        }


        #region 写文件日志


        private static readonly string logPath = Paths.BuildDataFilePath("log",
                                                                       string.Format("{0}.log",
                                                                                     DateTime.Now.ToString(
                                                                                         "yyyy-MM-dd")));

        private static readonly string logPathDir = Path.Combine(Paths.AppData, "log");
        private static object LockHelper = new object();
        /// <summary>
        /// 日志过期天数
        /// </summary>
        private static int OverDays = 90;

        private const int MaxLogNum = 5;

        private static List<string> ListLog = new List<string>(MaxLogNum);

        public static void WriteLogList(string msg)
        {
            lock (LockHelper)
            {
                ListLog.Add(msg);
            }
            if (ListLog.Count < MaxLogNum)
                return;
            WirteFile();
        }

        public static void WirteFile()
        {
            if (!Directory.Exists(logPathDir))
            {
                Directory.CreateDirectory(logPathDir);
            }

            lock (LockHelper)
            {
                using (StreamWriter sw = new StreamWriter(logPath, true))
                {
                    foreach (string msg in ListLog)
                    {
                        sw.WriteLine(msg);
                    }
                }
                ListLog.Clear();
            }
        }

        public static void DeleteOverTimeLog()
        {
            try
            {

                string[] arr = Directory.GetFiles(logPathDir);
                if (arr.Length == 0)
                    return;
                DateTime dt = DateTime.Now;

                foreach (string s in arr)
                {
                    string file = Path.GetFileName(s);
                    if (!file.Contains(".log"))
                        return;
                    string ds = file.Replace(".log", "");
                    try
                    {
                        DateTime dttemp = DateTime.Now;
                        bool bl = DateTime.TryParse(ds, out dttemp);
                        if (bl)
                        {
                            TimeSpan ts = dt - dttemp;
                            if (ts.Days > OverDays)
                            {
                                File.Delete(s);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        #endregion
    }
}
